//
//  SEExamineReserveViewController.swift
//  SmartEyeForPatient
//
//  Created by qdsg on 2021/4/8.
//

import UIKit

class SEExamineReserveViewController: SEBaseViewController {

    @IBOutlet weak var confirmBtnView: SERegistrationConfirmBtnView! {
        didSet {
            confirmBtnView.isHidden = true
            confirmBtnView.title = "提交"
            confirmBtnView.delegate = self
        }
    }

    @IBOutlet weak var tableView: UITableView! {
        didSet {
            tableView.isHidden = true
            tableView.tableFooterView = UIView()
            tableView.separatorColor = UIColor.init(hex: "EBECF0")
            tableView.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
            tableView.register(UINib(nibName: SEExamineReserveHospitalCell.className, bundle: nil), forCellReuseIdentifier: SEExamineReserveHospitalCell.reuseId)
            tableView.register(UINib(nibName: SEExamineReserveEyeTypeCell.className, bundle: nil), forCellReuseIdentifier: SEExamineReserveEyeTypeCell.reuseId)
            tableView.register(UINib(nibName: SEExamineReserveProjectCell.className, bundle: nil), forCellReuseIdentifier: SEExamineReserveProjectCell.reuseId)
            tableView.register(UINib(nibName: SERegistrationConfirmPatientCell.className, bundle: nil), forCellReuseIdentifier: SERegistrationConfirmPatientCell.reuseId)
            tableView.register(UINib(nibName: SEExamineReserveFeeCell.className, bundle: nil), forCellReuseIdentifier: SEExamineReserveFeeCell.reuseId)
        }
    }

    var viewModel = SEExamineReserveViewModel() {
        didSet {
            reloadData()
        }
    }

    init(with hospitalModel: SEHospitalListItem, checkSource: Int) {
        viewModel.hospitalModel = hospitalModel
        viewModel.checkSource = checkSource
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "检查预约"
        requestExamineItems()
        // Do any additional setup after loading the view.
    }

    override func setupUI() {
        super.setupUI()

        viewModel.updateData = { status in
            switch status {
            case .success:
                self.reloadData()
            case .auth(let msg):
                self.presentLoginViewController(selector: #selector(self.requestExamineItems)) {
                    SEHUD.showError(message: msg)
                }
            case .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }

        viewModel.submitHandler = { status in
            switch status {
            case .success:
                self.pushExaminOrderViewController()
            case .auth(let msg):
                self.presentLoginViewController(selector: #selector(self.requestExamineItems)) {
                    SEHUD.showError(message: msg)
                }
            case .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }
    }

    private func reloadData() {
        tableView.isHidden = false
        confirmBtnView.isHidden = false
        tableView.reloadData()
    }

    lazy var headerForSection: UIView = {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.screenWidth, height: 40))
        view.backgroundColor = UIColor.white
        let label = UILabel(frame: CGRect(x: 15, y: 0, width: UIScreen.screenWidth - 30, height: 20))
        label.centerY = view.centerY
        label.text = "选择检查项目（可选择多项）"
        label.font = UIFont.regular(14)
        label.textColor = Asset.textDark.color
        view.addSubview(label)
        return view
    }()


    /// 跳转就诊人列表

    private func pushPatientListViewController() {
        let vc = SEPatientListViewController(with: .select)
        vc.selectedHandler = {patientItem in
            let vm = self.viewModel
            vm.patientItem = patientItem
            self.viewModel = vm
        }
        navigationController?.pushViewController(vc, animated: true)
    }

    /// 时间日期选择器
    private func showDatePicker() {
        let picker = UINib.loadViewFrom(SEDatePicker.self)
        picker.dateStr = viewModel.applyCheckTime
        picker.delegate = self
        view.addSubview(picker)
    }

    private func pushExaminOrderViewController() {
        let vc = SEExamineOrderViewController(with: viewModel.applyFormId, fromType: .examineReserve)
        navigationController?.pushViewController(vc, animated: true)
    }

}

// MARK: - UITableViewDataSource, UITableViewDelegate

extension SEExamineReserveViewController: UITableViewDataSource, UITableViewDelegate {

    // MARK: - UITableViewDataSource

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 3 {
            return 2
        }
        return 1
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 5
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: SEExamineReserveHospitalCell.reuseId, for: indexPath) as! SEExamineReserveHospitalCell
            cell.updateCell(model: viewModel.hospitalModel)
            return cell
        }
        if indexPath.section == 1 {
            let cell = tableView.dequeueReusableCell(withIdentifier: SEExamineReserveEyeTypeCell.reuseId, for: indexPath) as! SEExamineReserveEyeTypeCell
            cell.delegate = self
            cell.updateCell(vm: viewModel)
            return cell
        }
        if indexPath.section == 2 {
            let cell = tableView.dequeueReusableCell(withIdentifier: SEExamineReserveProjectCell.reuseId, for: indexPath) as! SEExamineReserveProjectCell
            cell.delegate = self
            cell.updateCell(vm: viewModel)
            return cell
        }
        if indexPath.section == 3 {
            let cell = tableView.dequeueReusableCell(withIdentifier: SERegistrationConfirmPatientCell.reuseId, for: indexPath) as! SERegistrationConfirmPatientCell
            cell.updateCell(model: viewModel.entranceModelArray[indexPath.row])
            return cell
        }
        if indexPath.section == 4 {
            let cell = tableView.dequeueReusableCell(withIdentifier: SEExamineReserveFeeCell.reuseId, for: indexPath) as! SEExamineReserveFeeCell
            cell.updateCell(with: viewModel.totalFee)
            return cell
        }
        return UITableViewCell()
    }

    // MARK: - UITableViewDelegate

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        switch indexPath.section {
        case 0, 2: return UITableView.automaticDimension
        case 1, 3, 4: return 40
        default: return 0
        }
    }

    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 10
    }

    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView()
        view.backgroundColor = UIColor.clear
        return view
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        switch section {
        case 2:
            return 40
        default:
            return 0
        }
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return headerForSection
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard indexPath.section == 3 else { return }
        if indexPath.row == 0 {
            pushPatientListViewController()
        }
        if indexPath.row == 1 {
            showDatePicker()
        }
    }
}

// MARK: - SERegistrationConfirmBtnViewDelegate

extension SEExamineReserveViewController: SERegistrationConfirmBtnViewDelegate {
    func registrationConfirmBtnViewAction(view: SERegistrationConfirmBtnView) {
        requestSubmitExamine()
    }
}

// MARK: - SEExamineReserveEyeTypeCellDelegate

extension SEExamineReserveViewController: SEExamineReserveEyeTypeCellDelegate {
    func examineReserveEyeTypeCell(type: SEExamineReserveEyeType) {
        let vm = viewModel
        vm.checkEyeType = type
        viewModel = vm
    }
}

// MARK: - SEExamineReserveProjectCellDelegate

extension SEExamineReserveViewController: SEExamineReserveProjectCellDelegate {
    func examineReserveProjectCellItemAction(indexPath: IndexPath) {
        var itemModel = viewModel.checkItem(indexPath: indexPath)
        let selected = itemModel.isSelected
        itemModel.isSelected = !selected
        let vm = viewModel
        vm.replaceCheckItem(indexPath: indexPath, itemModel: itemModel)
        viewModel = vm
    }
}

// MARK: - SEDatePickerDelegate

extension SEExamineReserveViewController: SEDatePickerDelegate {
    func datePickerConfirmBtnAction(dateStr: String) {
        let vm = viewModel
        vm.applyCheckTime = dateStr
        viewModel = vm
    }
}

// MARK: - ApiRequest

extension SEExamineReserveViewController {
    @objc private func requestExamineItems() {
        viewModel.requestExamineItems()
    }

    @objc private func requestSubmitExamine() {
        viewModel.requestSubmitExamine()
    }
}
